import { AppDataSource } from './data_source'
import { createRoute, OpenAPIHono } from "@hono/zod-openapi"
import { RequestUserSchema, ResponseUserSchema } from './schemas/user'
import { swaggerUI } from '@hono/swagger-ui'
import { User } from './entity/user'

const app = new OpenAPIHono()

const route = createRoute({
  method: 'get',
  path: '/users',
  tags: ['User'],
  summary: 'Get all users',
  description: 'Returns a list of all users',
  request: {
    query: RequestUserSchema
  },
  responses: {
    200: {
      description: 'OK',
      content: {
        'application/json': {
          schema: ResponseUserSchema,
        },
      },
    },
  },
})

app.openapi(route, async (c) => {
  const users = await AppDataSource.getRepository(User).find()
  return c.json(users)
})

app.doc('/doc', {
  openapi: '3.0.0',
  info: {
    version: '1.0.0',
    title: 'My API',
  },
})

app.get('/ui', swaggerUI({ url: '/doc' }))

async function initialize() {
  try {
    await AppDataSource.initialize()
    console.log('Database connected')
  } catch (error) {
    console.error(error)
  }
}

initialize()

export default app
